<?php

namespace common\model\sell66;

use common\db\Sell66;

class UserOrderDetail extends Sell66 {
	// 设置当前模型对应的完整数据表名称
	protected $table = 'from_trade_detail';
	protected $pk = 'user_order_detail_id';
	public static function createUserOrderDetail($userOrderArr, $userOrderDetailData) {
		if (! $userOrderArr) {
			return false;
		}
		$userOrderDetailModel = new self ();
		$items = [ ];
// 		var_dump($userOrderDetailData);die;
		foreach ( $userOrderDetailData as $v ) {
			$items [] = [ 
					'user_order_id' => $userOrderArr ['user_order_id'],
					'type' => empty ( $userOrderDetailData ['type'] ) ?  : $userOrderDetailData ['type'],
					'o_id' => $v ['id'],
					'app_id' => $v ['appId'],
					'second' => $v ['item_second'],
					'class_id' => $v ['classid'],
					'instance_id' => $v ['instanceid'],
					'amount' => $v ['amount'],
					'market_hash_name' => $v ['market_hash_name'],
					'market_name' => $v ['market_name'],
					'price' => $v ['price'] ,
					'plus_price'=> $v['plus_price'],
					'origin_price'=> $v ['originPrice'] ,
					'rarity_color' => $v['rarity'],
					'action_link'=> isset($v['desc']['market_actions'][0]['link']) ? $v['desc']['market_actions'][0]['link'] : '',
					
			];
		}
		unset ( $userOrderDetailData );
		$result = $userOrderDetailModel->saveAll ( $items );
		if (! $result) {
			return false;
		}
		
		return $result;
	}
	public static function getUserOrderDetail($userId, $orderNo, $page, $limit) {
		if (! $orderNo) {
			return false;
		}
		$userOrdreDetailModel = new self ();
		$condition = [ 
				'user_id' => $userId,
				'orderno' => $orderNo 
		];
		
		$result = $userOrdreDetailModel->alias ( 'd' )->join ( 'user_order o', 'o.user_order_id = d.user_order_id' )->field ( 'd.image, d.market_hash_name, d.price' )->where ( $condition )->page ( $page, $limit )->select ();
		return $result;
	}
	public static function getUserOrderDetailCount($userId, $orderNo) {
		if (! $orderNo) {
			return false;
		}
		$userOrdreDetailModel = new self ();
		$condition = [ 
				'user_id' => $userId,
				'orderno' => $orderNo 
		];
		
		$result = $userOrdreDetailModel->alias ( 'd' )->join ( 'user_order o', 'o.user_order_id = d.user_order_id' )->field ( 'd.image, d.market_hash_name, d.price' )->where ( $condition )->count ();
		return $result;
	}
	
	public static function getItemsByTime($startTime,$endTime,$appId=730){
		$sql = "SELECT ud.*,uo.plus_ratio,b.steam_account,uo.bot_id as 'bot_id',b.steam_account as 'steam_account',
				uo.steam_id as 'user_steamId',ud.origin_price as 'steam_price'
				FROM user_order_detail as ud
				LEFT JOIN user_order as uo ON ud.user_order_id = uo.user_order_id
				LEFT JOIN bots as b ON b.id = uo.bot_id
				WHERE uo.order_status = 2 
				and ud.app_id = ? 
				and uo.finished_time between ?  and ?
				ORDER BY uo.bot_id ASC";
		$params = array($appId,$startTime,$endTime);
		$result = (new self)->db()->query($sql,$params);
		return $result;		
	}

	public static function getBotIdsItemsByTime($startTime,$endTime){
		$sql = "SELECT  uo.bot_id,ud.app_id FROM user_order_detail as ud
				LEFT JOIN user_order as uo ON ud.user_order_id = uo.user_order_id
				WHERE uo.order_status = 2 and ud.app_id <> 730 and uo.finished_time between ?  and ?
				group by  uo.bot_id,ud.app_id";
		$params = array($startTime,$endTime);
		$result = (new self)->db()->query($sql,$params);
		$botIds = [];
		foreach ($result as $item){
			$botIds[$item['bot_id']][] = $item['app_id'];
		}
		return $botIds;
	}

	/**
	 * 获取时间范围内，订单bot_id，app_id分组信息
	 * @param  array $date 时间范围
	 * @param  int $botId 机器人ID
	 * @return object
	 */
	public static function getDaySliceOrderDetails(array $date, $botId)
	{
		$where = array(
			'o.order_status' => 2,
		);

		if ($botId) {
			$where['o.bot_id'] = $botId;
		}

		$orderDetailsModel = new self();

		$retult = $orderDetailsModel->alias ('d')
		->join('user_order o', 'o.user_order_id = d.user_order_id')->field('o.bot_id,d.app_id')->where($where)
		->where('o.finished_time between '.$date['startTime'].' and '.$date['lastTime'].'')
		->group('o.bot_id,d.app_id')->order('o.bot_id')->select();

		return $retult;
	}

	/**
	 * 获取时间范围内，物品数量
	 * @param  int $botId 机器人ID
	 * @param  int $oId 物品ID
	 * @param  int $classId
	 * @param  int $instanceId
	 * @param  array $date 时间范围
	 * @return object
	 */
	public static function getOrderDetailsNum($botId, $oId, $classId, $instanceId, $date)
	{
		$where = array(
			'o.order_status' => 2,
			'o.bot_id' => $botId,
			'd.new_assetid' => $oId,
			//'d.class_id' => $classId,
			//'d.instance_id' => $instanceId,
		);

		$orderDetailsModel = new self();

		$retult = $orderDetailsModel->alias ('d')
		->join('user_order o', 'o.user_order_id = d.user_order_id')->field('o.bot_id,d.app_id,d.class_id,d.instance_id')->where($where)
		->where('o.finished_time between '.$date['startTime'].' and '.$date['lastTime'].'')->count();

		return $retult;
	}

	public static function updateOrderByOrderId($orderId, $assetid, $newAssetid)
	{
		$where = array(
			'user_order_id' => $orderId,
			'o_id' => $assetid,
		);

		$field = array(
			'new_assetid' => $newAssetid,
		);

		return static::where($where)->update($field);
	}

	/**
	 * 获取订单详情数量
	 * @param  int $assetid 物品ID
	 * @param  int $newAssetid 新物品ID
	 * @return object
	 */
	public static function getOrderDetailsTotalsByAssetId($assetid, $newAssetid)
	{
		$where = array(
			'o_id' => $assetid,
			'new_assetid' => $newAssetid,
		);

		return static::where($where)->count();
	}

	/**
	 * 修改订单详情新的物品ID
	 * @param  int $assetid 物品ID
	 * @param  int $newAssetid 新物品ID
	 * @return object
	 */
	public static function updateOrderDetailsByAssetId($assetid, $newAssetid)
	{
		$where = array(
			'o_id' => $assetid,
		);

		$field = array(
			'new_assetid' => $newAssetid,
		);

		return static::where($where)->update($field);
	}

	/**
	 * 获取订单详情数量
	 * @param  int $newAssetid 新物品ID
	 * @return object
	 */
	public static function getOrderDetailsTotalsByNewAssetId($newAssetid)
	{
		$where = array(
			'new_assetid' => $newAssetid,
		);

		return static::where($where)->count();
	}

	/**
	 * 修改订单详情新的物品ID
	 * @param  int $oldAssetid 物品ID
	 * @param  int $newAssetid 新物品ID
	 * @return array
	 */
	public static function updateOrderDetailsByNewAssetId($oldAssetid, $newAssetid)
	{
		$where = array(
			'new_assetid' => $oldAssetid,
		);

		$field = array(
			'new_assetid' => $newAssetid,
		);

		return static::where($where)->update($field);
	}

    public static function getInStoreByUserId($userId){
        $results =  static::join('from_trade', 'from_trade.user_order_id = from_trade_detail.user_order_id')
            ->where('from_trade.user_id',"=",$userId)
            ->whereIn('tradeoffer_status',[UserOrder::$tradeOfferStatusMap['create'],UserOrder::$tradeOfferStatusMap['reading']])
            ->field('from_trade_detail.*')
            ->select();
        $res = [];
        if(empty($results)){
            return $res;
        }
        foreach($results as $item){
            $res[$item['o_id']] = $item;
        }
        return $res;
    }
}